from django.http import JsonResponse
import json

def JR(data,*args,**kwargs):
    return JsonResponse(data,*args,json_dumps_params={'ensure_ascii': False},**kwargs)

class BaseRequestHandle:
    def handle(self,request):
        if request.method == 'GET':
            pd = request.GET
        else:
            pd = json.loads(request.body)

        request.pd = pd

        action = request.pd.get('action')

        handler = self.action_table.get(action)
        if handler is None:
            return JR({'ret': 2, 'msg': 'action 参数错误'})

        return handler(request)

    @staticmethod
    def login_required(func):
        def wrapper(self,request,*args,**kwargs):
            if request.session.get('usertype') is None:
                return JR({
                    'ret': 302,
                    'msg': '未登陆'})

            return func(self, request, *args, **kwargs)
        return wrapper

    @staticmethod
    def admin_required(func):
        def wrapper(self, request, *args, **kwargs):

            if request.session.get('usertype') != 1:
                return JR({
                    'ret': 402,
                    'msg': '用户必须是管理员类型'})

            return func(self,request,*args,**kwargs)
        return wrapper

    @staticmethod
    def StuTea_required(func):
        def wrapper(self,request,*args,**kwargs):

            if request.session['usertype'] != 2000\
                    and request.session['usertype'] != 3000:
                return JR({'ret':1,'msg':'该功能仅对老师与学生开放'})

            return func(self,request,*args,**kwargs)
        return wrapper

    @staticmethod
    def student_required(func):
        def wrapper(self,request,*args,**kwargs):

            if request.session['usertype'] != 2000:
                return JR({'ret':1,'msg':'该功能仅对学生开放'})

            return func(self,request,*args,*kwargs)
        return wrapper



